package GoodsService

import (
	"context"
	"database/sql"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/request/GoodsReq"
	"gdshop-admin-go-api/app/response/GoodsResp"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func getSkuSpecsItemBySpecIds(ctx context.Context, specId []int) []*GoodsResp.SpecLeaf {
	var listTmp []*GoodsResp.SpecLeaf
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_spec_item").Where("spec_id",
		specId).Order("display_sort DESC").Fields("id,title AS value,thumb,spec_id").
		Structs(&listTmp)
	if err != nil {
		return nil
	}
	return listTmp
}

func getSkuSpecsByGoodsId(ctx context.Context, goodsId int) []g.Map {
	var resList []*entity.GoodsSpec
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_spec").Where("goods_id",
		goodsId).Order("display_sort DESC").Structs(&resList)
	if err != nil {
		return []g.Map{}
	}

	resMap := g.List{}
	ids := []int{}
	for _, item := range resList {
		ids = append(ids, item.Id)
	}
	leafs := getSkuSpecsItemBySpecIds(ctx, ids)

	for _, item := range resList {
		resMap = append(resMap, g.Map{
			"id":    gconv.String(item.Id),
			"value": item.Title,
			"leaf": func() []*GoodsResp.SpecLeaf {
				var tmp = []*GoodsResp.SpecLeaf{}
				for _, ss := range leafs {
					if ss.SpecId == item.Id {
						tmp = append(tmp, ss)
					}
				}
				return tmp
			}(),
		})
	}

	return resMap
}
func getOptionsByGoodsId(ctx context.Context, goodsId int) []*entity.GoodsOption {
	var resList []*entity.GoodsOption
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_option").Where("goods_id",
		goodsId).Order("display_sort DESC").Structs(&resList)
	if err != nil {
		return resList
	}
	return resList
}
func getOptionPrice(price int64) float64 {
	return float64(price) / float64(100)
}
func getSkuOptionsArrByGoodsId(ctx context.Context, goodsId int) []g.Map {
	options := getOptionsByGoodsId(ctx, goodsId)
	resMap := g.List{}
	for _, item := range options {
		resMap = append(resMap, g.Map{
			"id":           gconv.String(item.Id),
			"thumb":        item.Thumb,
			"stock":        item.Stock,
			"market_price": getOptionPrice(item.MarketPrice),
			"sell_price":   getOptionPrice(item.SellPrice),
			"cost_price":   getOptionPrice(item.CostPrice),
			"goods_sku":    item.GoodsSn,
			"is_open":      item.IsOpen == 1,
			"specs":        item.Specs,
		})
	}

	return resMap
}

func Info(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	obj := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods").As("g").WherePri(
		"id",
		req.Id,
	).Fields("g.*,ge.goods_thumbs,ge.goods_content AS content,ge.goods_mobile_content AS mobile_content").
		LeftJoin("goods_extend ge", "ge.goods_id = g.id")

	res, err := obj.One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	resMap := res.Map()
	// 信息处理
	goodsThumbs := gconv.String(resMap["goods_thumbs"])
	if len(goodsThumbs) > 0 {
		thumbs := strings.Split(goodsThumbs, ",")
		if len(thumbs) < 1 {
			resMap["thumbs"] = g.Slice{}
		} else {
			resMap["thumbs"] = thumbs
		}
	} else {
		resMap["thumbs"] = g.Slice{}
	}
	resMap["category_id"] = gconv.Int(strings.Trim(gconv.String(resMap["cates"]), ","))
	allowAttrs := []string{
		"is_recommand",
		"is_new",
		"is_hot",
		"is_show_stock",
		"is_show_sales",
	}
	checkAttrs := []string{}
	for _, item := range allowAttrs {
		if gconv.Int(resMap[item]) > 0 {
			checkAttrs = append(checkAttrs, item)
		}
		delete(resMap, item)
	}
	resMap["check_attrs"] = checkAttrs

	delete(resMap, "cates")
	delete(resMap, "goods_thumbs")

	delete(resMap, "delete_at")

	goodsId := gconv.Int(req.Id)
	// 获取附加信息 specs
	resMap["specs"] = getSkuSpecsByGoodsId(ctx, goodsId)
	resMap["options"] = getSkuOptionsArrByGoodsId(ctx, goodsId)
	//resMap["mobile_content"] = []string{}
	var mcTmps []*GoodsReq.MobileContentItem
	err = gconv.Structs(resMap["mobile_content"], &mcTmps)
	if err == nil {
		if mcTmps == nil {
			resMap["mobile_content"] = []string{}
		} else {
			resMap["mobile_content"] = mcTmps
		}
	} else {
		resMap["mobile_content"] = []string{}
	}

	resMap["attributes"] = getGoodsAttribute(ctx, goodsId)

	return response.SuccessByRequestMessageData(nil, "获取成功",
		resMap)
}

func getGoodsAttribute(ctx context.Context, goodsId int) g.List {
	all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_attribute").Where("attribute_type=1 AND goods_id = ?", goodsId).
		Fields("icon_name,icon_text").All()
	if err != nil {
		return g.List{}
	}

	return all.List()
}
